package com.example.waterdispenserm2.mo.water;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityHob2DisplayBoardBinding;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Hob2DisplayBoardActivity extends BasicsActivity<ActivityHob2DisplayBoardBinding> implements  Hob2DisplayBoard.DisplayCallback{

    private Hob2DisplayBoard displayBoard;


    // 日志相关
    private StringBuilder logBuilder = new StringBuilder();
    private static final int MAX_LOG_LINES = 100;
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {

        // 初始化视图
        initViews();


// 初始化显示板通信
        displayBoard = new Hob2DisplayBoard();
        // 串口选择逻辑
        binding.btOpen.setOnClickListener(v -> {
            String input = binding.etAdd.getText().toString().trim();
            String path = "/dev/ttyS0"; // 默认路径

            if (!TextUtils.isEmpty(input)) {
                switch (input) {
                    case "0": path = "/dev/ttyS0"; break;
                    case "1": path = "/dev/ttyS1"; break;
                    case "2": path = "/dev/ttyS2"; break;
                    case "3": path = "/dev/ttyS3"; break;
                    case "4": path = "/dev/ttyS4"; break;
                    case "5": path = "/dev/ttyS5"; break;
                    case "6": path = "/dev/ttyS6"; break;
                    case "7": path = "/dev/ttyS7"; break;
                }
            }
            displayBoard.init(path, 9600, this);
        });

        binding.btClase.setOnClickListener(v->{onDestroy();});
        binding.ivMessage.setOnClickListener(v->{finish();});



        setupButtonListeners();
    }

    @Override
    protected ActivityHob2DisplayBoardBinding getViewBinding() {
        return ActivityHob2DisplayBoardBinding.inflate(LayoutInflater.from(this));
    }


    @SuppressLint("WrongViewCast")
    private void initViews() {
        // 添加初始日志
        appendLog("应用启动");
        appendLog("正在初始化串口...");

    }



    @SuppressLint("ClickableViewAccessibility")
    private void setupButtonListeners() {

        // 创建触摸监听器
        View.OnTouchListener keyTouchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int keyCode = Hob2DisplayBoard.KEY_NONE;

                // 根据按钮ID确定按键值
                if (v.getId() == R.id.btn_power) {
                    keyCode = Hob2DisplayBoard.KEY_POWER;
                } else if (v.getId() == R.id.btn_timer) {
                    keyCode = Hob2DisplayBoard.KEY_TIMER;
                } else if (v.getId() == R.id.btn_function) {
                    keyCode = Hob2DisplayBoard.KEY_FUNCTION;
                } else if (v.getId() == R.id.btn_dec) {
                    keyCode = Hob2DisplayBoard.KEY_DEC;
                } else if (v.getId() == R.id.btn_inc) {
                    keyCode = Hob2DisplayBoard.KEY_INC;
                } else if (v.getId() == R.id.btn_start) {
                    keyCode = Hob2DisplayBoard.KEY_START;
                }

                // 处理触摸事件
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        displayBoard.sendKeyEvent(keyCode);
                        return true;
                    case MotionEvent.ACTION_UP:
                        displayBoard.sendKeyRelease();
                        return true;
                }
                return false;
            }
        };
        // 为按钮设置触摸监听
        binding.btnPower.setOnTouchListener(keyTouchListener);
        binding.btnTimer.setOnTouchListener(keyTouchListener);
        binding.btnFunction.setOnTouchListener(keyTouchListener);
        binding.btnDec.setOnTouchListener(keyTouchListener);
        binding. btnInc.setOnTouchListener(keyTouchListener);
        binding. btnStart.setOnTouchListener(keyTouchListener);
    }

    @Override
    public void onDisplayUpdate(byte[] digitSegments, byte ledStatus) {
        runOnUiThread(() -> {
            // 更新数码管显示
            binding.digit1.setText(Hob2DisplayBoard.segmentToDigit(digitSegments[0]));
            binding.digit2.setText(Hob2DisplayBoard.segmentToDigit(digitSegments[1]));
            binding.digit3.setText(Hob2DisplayBoard.segmentToDigit(digitSegments[2]));
            binding.digit4.setText(Hob2DisplayBoard.segmentToDigit(digitSegments[3]));

            // 更新LED指示灯
            updateLed(binding.ledFrying, ledStatus, Hob2DisplayBoard.LED_FRYING);
            updateLed(binding.ledPorridge, ledStatus, Hob2DisplayBoard.LED_PORRIDGE);
            updateLed(binding.ledHotpot, ledStatus, Hob2DisplayBoard.LED_HOTPOT);
            updateLed(binding.ledHighFire, ledStatus, Hob2DisplayBoard.LED_HIGH_FIRE);
            updateLed(binding.ledLowFire, ledStatus, Hob2DisplayBoard.LED_LOW_FIRE);
            updateLed(binding.ledWater, ledStatus, Hob2DisplayBoard.LED_WATER);
            updateLed(binding.ledSteam, ledStatus, Hob2DisplayBoard.LED_STEAM);
            updateLed(binding.ledSoup, ledStatus, Hob2DisplayBoard.LED_SOUP);

            // 记录收到的数据
            String dataLog = "更新显示: " +
                    "数码管: [" + formatDigitDisplay(digitSegments) + "], " +
                    "LED状态: " + formatByte(ledStatus);

            appendLog(dataLog);
        });
    }

    // 更新LED指示灯状态
    private void updateLed(ImageView ledView, byte ledStatus, int ledPosition) {
        boolean isOn = ((ledStatus >> (7 - ledPosition)) & 0x01) == 1;
        ledView.setColorFilter(isOn ?
                Color.parseColor("#FF5722") : // 亮起状态(橙色)
                Color.parseColor("#CCCCCC")); // 熄灭状态(灰色)
    }

    @Override
    public void onDataError(String message) {
        runOnUiThread(() -> {
            appendLog("错误: " + message);
        });
    }

    @Override
    public void logMessage(String message) {
        appendLog(message);
    }

    // 添加日志方法
    private void appendLog(final String message) {
        runOnUiThread(() -> {
            // 添加时间戳
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
            String timestamp = sdf.format(new Date());

            // 格式化为日志行
            String logLine = "[" + timestamp + "] " + message + "\n";

            // 添加到日志缓存
            logBuilder.append(logLine);

            // 限制日志行数
            if (logBuilder.toString().split("\n").length > MAX_LOG_LINES) {
                int firstNewline = logBuilder.indexOf("\n") + 1;
                logBuilder.delete(0, firstNewline);
            }

            // 更新TextView
            binding.txtLog.setText(logBuilder.toString());

            // 自动滚动到底部
            binding.logScroll.post(() -> binding.logScroll.fullScroll(View.FOCUS_DOWN));
        });
    }

    // 格式化数码管显示内容
    private String formatDigitDisplay(byte[] segments) {
        StringBuilder sb = new StringBuilder();
        for (byte seg : segments) {
            sb.append(Hob2DisplayBoard.segmentToDigit(seg));
        }
        return sb.toString();
    }

    // 格式化单个字节为十六进制字符串
    private String formatByte(byte b) {
        return String.format("0x%02X", b);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (displayBoard != null) {
            displayBoard.close();
        }
    }
}